package com.projecy.logs.ascept;


import com.projecy.common.utils.RequestHolder;
import com.projecy.common.utils.SecurityUtil;
import com.projecy.common.utils.StringUtil;
import com.projecy.common.utils.ThrowsUtil;
import com.projecy.system.model.SysLog;
import com.projecy.system.service.SysLogService;
import com.projecy.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    SysLogService sysLogService;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();


    public LogAspect(SysLogService sysLogService){
        this.sysLogService = sysLogService;
    }

    // 配置切入点
    @Pointcut("@annotation(com.projecy.logs.annotation.Log)")
    public void logPointcut(){

    }


    @Around("logPointcut()")//配置环绕通知,使用在方法logPointcut()上注册的切入点
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕通知");
        Object result;
        currentTime.set(System.currentTimeMillis());
        result = joinPoint.proceed();
        SysLog sysLog = new SysLog("1",System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        sysLogService.save(getUsername(), StringUtil.getIp(request),joinPoint, sysLog);
        return result;
    }


    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")//配置异常通知
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e){
        System.out.println("配置异常通知");
        SysLog sysLog = new SysLog("2",System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        sysLog.setExceptionDetail(ThrowsUtil.getStackTrace(e));
        HttpServletRequest request = RequestHolder.getHttpServletRequest();
        sysLogService.save(getUsername(), StringUtil.getIp(request), (ProceedingJoinPoint)joinPoint, sysLog);
    }


    public String getUsername() {//获取当前登录用户名
        System.out.println("获取当前登录用户名");
        try {
            return SecurityUtil.getCurrentUsername();
        }catch (Exception e){
            return "";
        }
    }
}
